package com.oolee.cloud.controller;


import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.oolee.cloud.entity.Payment;
import com.oolee.cloud.general.GeneralResult;
import com.oolee.cloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;


@RestController
@Slf4j
@DefaultProperties(defaultFallback = "globalFallback")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;


    @PostMapping(value = "/payment/create")
    public GeneralResult<Integer> create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("*******插入结果："+result);
        return result>0 ?
                new GeneralResult<>(1002,"插入payment成功,port: "+serverPort,result):
                new GeneralResult<>(1444,"插入payment失败",null);
    }

    @GetMapping(value = "/payment/get/{id}")
    public GeneralResult<Payment> getPaymentById(@PathVariable("id")Long id){
        Payment payment = paymentService.getPaymentById(id);
        log.info("*******返回结果："+payment+"********");
        return payment != null ?
                new GeneralResult<>(1002,"查询payment成功,port: "+serverPort,payment):
                new GeneralResult<>(1444,"没有对应记录,查询id："+id,null);
    }

    @GetMapping(value = "/payment/discovery")
    public Object getDiscovery(){
        List<String> services = discoveryClient.getServices();
        for (String service:services){
            log.info("******service: "+service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance:instances){
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }

        return discoveryClient;
    }

    @GetMapping(value = "/payment/timeout")
    public String TimeOutShow(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "timeout 3s";
    }

    @GetMapping(value = "/payment/exception")
    @HystrixCommand
    public String requestException(){
        int num = 10/0;
        return "不可能返回这段话。。。";
    }

    public String globalFallback(){
        return "globalFallback --> o(╥﹏╥)o 请求异常,请稍后重试";
    }
}
    